package cn.czg.cms.netty;

import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.AttributeKey;

import java.util.concurrent.TimeUnit;

public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final NettyChannelManager nettyChannelManager;

    public WebSocketChannelInitializer(NettyChannelManager nettyChannelManager) {
        this.nettyChannelManager = nettyChannelManager;
    }

    @Override
    protected void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();

        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new HttpObjectAggregator(65536));

        // 👇 必须添加：记录 URI 到 AttributeKey
        pipeline.addLast(new SimpleChannelInboundHandler<FullHttpRequest>() {
            @Override
            protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
                ctx.channel().attr(AttributeKey.valueOf("uri")).set(msg.uri());
                ctx.fireChannelRead(msg.retain()); // 非常重要：retain 后传递
            }
        });

        // 👇 Netty 的 WebSocket 协议处理器
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws/chat"));

        // 👇 你的握手处理器
        pipeline.addLast(new WebSocketHandshakeHandler(nettyChannelManager));

        // 👇 消息解码器
        pipeline.addLast(new MessageDecoder());

        // 👇 你的主业务逻辑 handler
        pipeline.addLast(new WebSocketHandler(nettyChannelManager));
    }


}
